import React from 'react';
import dayjs from "dayjs";

// 根据文件流下载文件
export const downloadFile = (response: Response, name?: string) => {
    const blob: Blob = new Blob([response.data]); //生成blob
    const link: HTMLAnchorElement = document.createElement("a");
    const href: string = window.URL.createObjectURL(blob); //创建URL
    let fileName: string | number = ''
    if (!name) {
        const disposition: string | null = response.headers.get("content-disposition");
        fileName = disposition ? decodeURIComponent(disposition.split("=")[1]) : new Date().getTime(); //分割字符串，拿到文件名
    } else {
        fileName = name
    }
    link.href = href;
    link.download = String(fileName); //文件名转码
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(href);
}
// 根据文件流下载文件
export const downloadFileForUrl = (url: string, fileName) => {
    fetch(import.meta.env.VITE_BASE_IMG + url).then((res) => {
        res.blob().then((blob) => {
            const blobUrl = window.URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = blobUrl;
            a.download = fileName;
            a.click();
            window.URL.revokeObjectURL(blobUrl);
        });
    });
}
// 级联选择器根据叶子节点值查找完整路径
export const radioFindPathByLeafValue = (leafValue: string, options: [], code: string = 'orgCode', childrenKey: string = 'children'): [] => {
    const path: [] = []

    const traverse = (nodes: []) => {
        for (const node of nodes) {
            path.push(node[code]);

            // 如果是叶子节点且匹配
            if (node[code] === leafValue) {
                return true;
            }

            // 递归查找子节点
            if (node[childrenKey] && traverse(node[childrenKey])) {
                return true;
            }

            // 回溯
            path.pop();
        }
        return false;
    };

    traverse(options);
    return path;
};

export const multipleFindPathByLeafValue = (leafValues: string[], options: [], code: string = 'orgCode', childrenKey: string = 'children'): [] => {
    const list: [] = []
    leafValues.forEach(leafValue => {
        const item: [] = radioFindPathByLeafValue(leafValue, options, code, childrenKey)
        list.push(item);
    })
    return list
};

export const formatToDayJs = (lists, obj) => {
    lists.forEach(key => {
        obj[key]&&(obj[key] = dayjs(obj[key]))
    })
}
export const formatFormDayJs = (lists, obj) => {
    lists.forEach(key => {
        obj[key]&&(obj[key] = dayjs(obj[key]).format('YYYY-MM-DD'))
    })
}
// 递归找数据
export const findIByCodeRecursion = (arr, targetCode, children) => {
    for (const item of arr) {
        if (item.orgCode === targetCode) {
            return item;
        }
        if (item[children] && Array.isArray(item[children]) && item[children].length > 0) {
            const found = findIByCodeRecursion(item[children], targetCode);
            if (found) return found;
        }
    }
    return null;
}
// 根据图片的宽度计算弹框宽度
export const checkTheWidthOfTheProgressPopUpBox = (progressImg, width: string = '1260px') => {
    let dialogWidth = width
    return new Promise((resolve, reject) => {
        var img = new Image();
        img.src = progressImg
        img.onload = () => {
            // 当图像加载完成后进行resolve
            // 获取图片宽度和高度
            let imgWidth = img.width
            let maxWidth = document.documentElement.clientWidth - 200
            if (imgWidth > maxWidth) {
                dialogWidth = maxWidth
            } else {
                dialogWidth = imgWidth
            }
            dialogWidth += 40
            dialogWidth += 'px'
            resolve(dialogWidth)
        }
        img.onerror = () => {
            reject(new Error('图像加载失败'))
        }
    })
}
//数据转成树结构
// export const addressTreeData = (data) => {
//         var tmp = {},
//             parent, n;
//         for (let i = 0; i < data.length; i++) {
//             let item = data[i];
//             if (item.areaCode == item.parentCode) {
//                 parent = item.areaCode;
//             }
//             if (!tmp[item.areaCode]) {
//                 tmp[item.areaCode] = {};
//             }
//             tmp[item.areaCode].areaName = item.areaName;
//             tmp[item.areaCode].areaCode = item.areaCode;
//             if (!("children" in tmp[item.areaCode])) tmp[item.areaCode].children = [];
//
//             if (item.areaCode != item.parentCode) {
//                 if (tmp[item.parentCode]) {
//                     // console.log(tmp[item.parentCode], "数据")
//                     tmp[item.parentCode].children.push(tmp[item.areaCode]);
//                 } else {
//                     // console.log("245")
//                     tmp[item.parentCode] = {children: [tmp[item.areaCode]]};
//                 }
//             }
//         }
//         return tmp[0].children;
//     }
